<route lang="json5" type="home">
{
  layout: "tabbar",
  style: {
    navigationBarTitleText: "主页",
    navigationStyle: "custom",
  },
}
</route>
<template>
  <wd-toast />
  <view
    v-if="!loading && defaultShowFlag"
    class="overflow-hidden home-container"
  >
    <view class="home-bg">
      <image
        class="h-[500rpx] w-100%"
        :src="basicInfo.bgImg"
        mode="aspectFill"
      />
      <!-- src="/static/images/bg.png" -->
      <view class="home-bg-inner" @click.stop="chooseBackgroundImage">
        <view
          class="flex items-center m-b-12rpx"
          :style="{
            marginTop: topHeight,
          }"
        >
          <image
            v-if="basicInfo.coverImage"
            class="h-[120rpx] w-[120rpx]"
            style="border-radius: 50%"
            :src="basicInfo.coverImage"
            mode="aspectFill"
            @click.stop="chooseAvatarImage"
          />

          <image
            v-else
            class="h-[120rpx] w-[120rpx] b-r-8rpx"
            src="/static/images/labava.png"
            mode="aspectFill"
            @click="chooseAvatarImage"
          />
          <!-- src="/static/images/labava.png" -->
          <view class="pl-20rpx">
            <view class="text-34rpx mb-8rpx" @click.stop="chooseNickname">{{
              basicInfo.unionName
            }}</view>
            <view class="text-24rpx text-[rgba(255,255,255,0.8)]">
              {{ basicInfo.introduction }}
            </view>
          </view>
        </view>
        <view class="flex justify-between items-center">
          <view class="flex flex-1">
            <view class="text-center pr-30rpx" @click.stop="goFans">
              <view class="text-34rpx">{{
                basicInfo.fansCount > 0 ? basicInfo.fansCount : 0
              }}</view>
              <view class="text-24rpx text-[rgba(255,255,255,0.8)]">粉丝</view>
            </view>
          </view>
          <button
            class="bg-#B8F069 text-#1b1b1b text-24rpx font-bold p-l-20rpx p-r-20rpx rounded-32rpx"
            open-type="share"
            @click.stop=""
          >
            邀请入会
          </button>
        </view>
      </view>
    </view>
    <view class="home-container-inner pb-10">
      <view
        v-if="informationList.length || activityList.length"
        class="tabContent"
      >
        <view
          class="tabItem"
          :class="activeTab === item.value ? 'tabItemAct' : ''"
          v-for="item in tabList"
          :key="item.value"
          @click="changeTab(item.value)"
        >
          {{ item.label }}
        </view>
      </view>

      <view v-if="activeTab === 1" class="scroll-container">
        <view
          v-for="item in activityList"
          :key="item"
          class="scroll-item m-t-25rpx m-b-50rpx img-box rounded-[20rpx] bg-[rgba(0,0,0,0.8)]"
          @click="goActivityDetail(item)"
        >
          <image mode="aspectFill" class="img" :src="item.coverImage" />
          <view
            class="img-text w-[100%] bottom-0 text-white text-shadow-md text-outline box-border"
          >
            <view
              class="text-[30rpx] p-2 bg-black bg-opacity-20 font-bold flex justify-between ellipsis-3-lines"
            >
              <text class="ellipsis-3-lines">{{ item.title }}</text>
              <!-- <view
                class="text-[16rpx] h-[34rpx] font-normal rounded-full bg-black text-white justify-center flex items-center px-[12rpx] box-border"
              >
                87人评论
              </view> -->
            </view>
            <!-- <text class="text-[24rpx]">{{item.description}}</text> -->
          </view>
        </view>
      </view>
      <view v-if="activeTab === 2" class="scroll-container">
        <view
          v-for="item in informationList"
          :key="item"
          class="scroll-item m-t-25rpx m-b-50rpx img-box rounded-[20rpx] bg-[rgba(0,0,0,0.8)]"
          @click="goInforDetail(item)"
        >
          <image mode="aspectFill" class="img" :src="item.coverImage" />
          <view
            class="img-text w-[100%] bottom-0 text-white p-[16rpx] box-border"
          >
            <view class="text-[30rpx] font-bold flex justify-between">
              <text>{{ item.title }}</text>
              <!-- <view
                class="text-[16rpx] h-[34rpx] font-normal rounded-full bg-black text-white justify-center flex items-center px-[12rpx] box-border"
              >
                87人评论
              </view> -->
            </view>
            <!-- <text class="text-[20rpx]">{{item.description}}</text> -->
          </view>
        </view>
      </view>
      <view class="p-l-26rpx p-r-26rpx">
        <!-- <view class="flex justify-between home-title-bg">
          <view class="text-36rpx text-#000 font-bold">大梦简历</view>
          <view class="flex line-content">
            <view class="line-item"></view>
            <view class="line-item"></view>
            <view class="line-item"></view>
          </view>
        </view> -->
        <view v-html="basicInfo.workReport"></view>
        <!-- <image
          class="h-[500rpx] w-100%"
          src="/static/images/bg.png"
          mode="aspectFill"
        /> -->

        <view
          v-if="
            superManagerPermission(userInfo.role) ||
            managerPermission(userInfo.role)
          "
          @click="editHome"
          class="edit-btn bg-#B8F069 text-#1b1b1b text-24rpx font-bold p-t-20rpx p-b-20rpx rounded-32rpx"
        >
          编辑
        </view>
      </view>
    </view>
    <uni-popup
      ref="popupNickName"
      type="center"
      background-color="#fff"
      border-radius="20px 20px 20px 20px"
      class="my-nick-pop"
    >
      <view class="my-nick-pop-title">修改名称</view>
      <view class="my-nick-pop-input">
        <input
          type="nickname"
          :value="basicInfo.unionName"
          placeholder="请输入名称"
          @input="nickChange"
          @blur="nickChange"
        />
      </view>
      <view class="my-nick-pop-btn">
        <button @click="cancelUserInfo">取消</button>
        <button class="my-nick-pop-btn-sure" @click="changeUserInfo">
          确定
        </button>
      </view>
    </uni-popup>
    <uni-popup
      ref="popupSignature"
      type="center"
      background-color="#fff"
      border-radius="20px 20px 20px 20px"
      class="my-nick-pop"
    >
      <view class="my-nick-pop-title">修改描述</view>
      <view class="my-nick-pop-input">
        <input
          type="nickname"
          :value="basicInfo.slogan"
          placeholder="请输入描述"
          @input="signatureChange"
          @blur="signatureChange"
        />
      </view>
      <view class="my-nick-pop-btn">
        <button @click="canceSignature">取消</button>
        <button class="my-nick-pop-btn-sure" @click="changeSignature">
          确定
        </button>
      </view>
    </uni-popup>
  </view>
</template>
<script lang="ts" setup>
import {
  computed,
  onMounted,
  watch,
  reactive,
  ref,
} from "@/uni_modules/lime-shared/vue";
import {
  httpGetBasicInfoDetail,
  httpGetInformationList,
  httpGetActivityList,
  httpUpdateBasicInfo,
} from "@/service/home";
import defaultImage from "@/static/images/labava.png";
import { onShareAppMessage } from "@dcloudio/uni-app";
import { superManagerPermission, managerPermission } from "@/utils";
import { useUserStore } from "@/store";
import { storeToRefs } from "pinia";
import { useToast } from "wot-design-uni";

const toast = useToast();
const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL;
const isStretchedScreen = ref<Boolean>(false);
const topHeight = ref<String>("");
const activeTab = ref<Number>(1);
const tabList = ref<any>([]);
const loading = ref<boolean>(false);
let basicInfo = ref<any>({});
let activityList = ref<any>([]);
let informationList = ref<any>([]);
const defaultShowFlag = ref<boolean>(false);
const popupNickName = ref<any>(null);
const nick = ref("");
const popupSignature = ref<any>(null);
const signature = ref("");
const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
console.log("userInfo", userInfo);
const previewImage = (url) => {
  uni.previewImage({
    current: 0, // 当前显示的图片
    urls: [url], // 预览的图片列表
  });
};

const goFans = () => {
  uni.navigateTo({
    url: "/pages-sub/fans-page/index",
  });
};

const editHome = () => {
  uni.navigateTo({
    url: "/pages-sub/homeEdit/index",
  });
};

// 修改昵称
const chooseNickname = () => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    popupNickName.value.open("center");
  }
};
const cancelUserInfo = () => {
  popupNickName.value.close();
};
const nickChange = (v: any) => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    nick.value = v?.detail?.value;
  }
};
const changeUserInfo = async () => {
  try {
    const res: any = await httpUpdateBasicInfo({
      id: 1,
      unionName: nick.value,
    });
    if (res.code === 200) {
      toast.show("操作成功");
      basicInfo.value.unionName = nick.value;
      popupNickName.value.close();
    } else {
      toast.show(res.msg);
    }
  } catch (error) {
    console.log(error, "error");
  }
};

// 修改slogan
const chooseDescription = () => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    popupSignature.value.open("center");
  }
};
const canceSignature = () => {
  popupSignature.value.close();
};
const signatureChange = (v: any) => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    signature.value = v?.detail?.value;
  }
};
const changeSignature = async () => {
  try {
    const res: any = await httpUpdateBasicInfo({
      id: 1,
      slogan: signature.value,
    });
    if (res.code === 200) {
      toast.show("操作成功");
      basicInfo.value.slogan = signature.value;
      popupSignature.value.close();
    } else {
      toast.show(res.msg);
    }
  } catch (error) {
    console.log(error, "error");
  }
};

const chooseAvatarImage = () => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    uni.chooseMedia({
      count: 1,
      mediaType: ["image"],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        uni.uploadFile({
          url: VITE_UPLOAD_BASEURL,
          name: "file",
          filePath: tempFilePath,
          header: {
            "content-type": "multipart/form-data",
            "Blade-Auth": "Bearer " + userInfo.value.token,
          },
          success: async (res: any) => {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              const data = JSON.parse(res.data);
              if (data.code !== 200) {
                uni.showToast({
                  icon: "none",
                  title: data.msg || "请求错误",
                });
                if (data.code === 401) {
                  uni.clearStorageSync();
                  uni.navigateTo({ url: "/pages/login/index" });
                }
              } else {
                const res: any = await httpUpdateBasicInfo({
                  id: 1,
                  coverImage: data.data.link,
                });
                if (res.code === 200) {
                  basicInfo.value.coverImage = data.data.link;
                  toast.show("操作成功");
                }
              }
            } else {
              uni.showToast({
                icon: "none",
                title: res.errMsg || "请求错误",
              });
            }
          },
          fail: (err) => {
            uni.showToast({
              icon: "none",
              title: err.errMsg,
            });
          },
        });
      },
      fail: (err) => {
        // uni.showToast({
        //   icon: "none",
        //   title: err.errMsg,
        // });
      },
    });
  } else {
    previewImage(basicInfo.coverImage || defaultImage);
  }
};

const chooseBackgroundImage = () => {
  if (
    superManagerPermission(userInfo?.value?.role) ||
    managerPermission(userInfo?.value?.role)
  ) {
    uni.chooseMedia({
      count: 1,
      mediaType: ["image"],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        uni.uploadFile({
          url: VITE_UPLOAD_BASEURL,
          name: "file",
          filePath: tempFilePath,
          header: {
            "content-type": "multipart/form-data",
            "Blade-Auth": "Bearer " + userInfo.value.token,
          },
          success: async (res: any) => {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              const data = JSON.parse(res.data);
              if (data.code !== 200) {
                uni.showToast({
                  icon: "none",
                  title: data.msg || "请求错误",
                });
                if (data.code === 401) {
                  uni.clearStorageSync();
                  uni.navigateTo({ url: "/pages/login/index" });
                }
              } else {
                const res: any = await httpUpdateBasicInfo({
                  id: 1,
                  bgImg: data.data.link,
                });
                if (res.code === 200) {
                  basicInfo.value.bgImg = data.data.link;
                  toast.show("操作成功");
                }
              }
            } else {
              uni.showToast({
                icon: "none",
                title: res.errMsg || "请求错误",
              });
            }
          },
          fail: (err) => {
            uni.showToast({
              icon: "none",
              title: err.errMsg,
            });
          },
        });
      },
      fail: (err) => {
        // uni.showToast({
        //   icon: "none",
        //   title: err.errMsg,
        // });
      },
    });
  }
};

const goInforDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages-sub/informationDetail/index?id=${item.id}`,
  });
};

const goActivityDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages-sub/activeDetail/index?id=${item.id}`,
  });
};

const getInformationList = async () => {
  try {
    const params = {
      current: 1,
      size: 10,
    };
    return await httpGetInformationList(params);
  } catch (error) {
    console.log(error, "error");
  }
};

const getActivityList = async () => {
  try {
    const params = {
      current: 1,
      size: 10,
    };
    return await httpGetActivityList(params);
  } catch (error) {
    console.log(error, "error");
  }
};

const getBasicInfoDetail = async () => {
  try {
    return httpGetBasicInfoDetail({ id: 1 });
  } catch (error) {
    console.log(error, "error");
  }
};

const resPromissAll = async () => {
  defaultShowFlag.value = false;
  try {
    loading.value = true;
    const [basicRes, informationRes, activityRes] = await Promise.all([
      getBasicInfoDetail(),
      getInformationList(),
      getActivityList(),
    ]);

    if (
      basicRes.code === 200 &&
      informationRes.code === 200 &&
      activityRes.code === 200
    ) {
      basicInfo.value = basicRes.data;
      informationList.value = informationRes.data.records;
      activityList.value = activityRes.data.records;

      if (activityRes.data.records.length > 0) {
        tabList.value.push({ label: "最新活动", value: 1 });
      }
      if (informationRes.data.records.length > 0) {
        tabList.value.push({ label: "最新资讯", value: 2 });
      }

      if (tabList.value.length > 0) {
        activeTab.value = tabList.value[0].value;
      }
    }
    defaultShowFlag.value = true;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.log(error, "error");
  }
};

onMounted(() => {
  // getBasicInfoDetail();
  // getInformationList();
  checkForNotch();
  resPromissAll();
});

const checkForNotch = () => {
  const sysInfo = uni.getSystemInfoSync();
  const notchHeight = 25;
  const statusBarHeight = sysInfo.statusBarHeight;
  if (statusBarHeight > notchHeight) {
    isStretchedScreen.value = true; // 是刘海屏
  } else {
    isStretchedScreen.value = false; // 不是刘海屏
  }
};

watch(
  () => isStretchedScreen.value,
  () => {
    if (isStretchedScreen.value) {
      topHeight.value =
        menuButtonInfo?.height + menuButtonInfo?.top + 50 + "rpx";
    } else {
      topHeight.value =
        menuButtonInfo?.height + menuButtonInfo?.top + 77 + "rpx";
    }
  },
  { immediate: true }
);

const changeTab = (val) => {
  activeTab.value = val;
};

onShareAppMessage((res: any) => {
  let obj: any = null;
  if (res?.from === "button") {
    obj = {
      title: "大梦创新",
      path: `/pages/login/index?invite=true`,
    };
  } else {
    obj = false;
  }
  return obj;
});
</script>

<style lang="scss" scoped>
.home-container {
  position: relative;
  min-height: 100vh;
  // padding-bottom: 30rpx;
  background: #fff;
  .ellipsis-3-lines {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* 限制最多显示2行 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .home-bg {
    position: relative;
    height: 428rpx;
  }
  .home-bg-inner {
    position: absolute;
    top: 0;
    left: 0;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 0 32rpx;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.6);
  }
  .home-container-inner {
    position: relative;
    z-index: 2;
    box-sizing: border-box;
    margin-top: -50rpx;
    background: #fff;
    border-radius: 40rpx;
    padding-top: 32rpx;

    .tabContent {
      display: flex;
      justify-content: flex-end;
      padding: 0 26rpx;
      .tabItem {
        border-radius: 210rpx;
        background: rgba(235, 247, 244, 1);
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding: 10rpx 16rpx 10rpx 16rpx;
        margin-right: 12rpx;
        font-size: 20rpx;
        font-weight: bold;
        letter-spacing: 0rpx;
        color: rgba(48, 69, 64, 1);
      }

      .tabItem:last-child {
        margin-right: 0;
      }

      .tabItemAct {
        background: rgba(184, 240, 105, 1);
      }
    }

    .scroll-container {
      display: flex;
      overflow-x: auto;
      padding: 0 35rpx;
      scrollbar-width: none;

      .scroll-item {
        // flex-shrink: 0;
        width: 334rpx;
        height: 334rpx;
        margin-right: 10px;
        margin-bottom: 10px;
        background-color: #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 20rpx;

        .img {
          width: 334rpx;
          height: 334rpx;
          border-radius: 20rpx;
        }
      }

      .scroll-item:last-child {
        margin-right: 0;
      }
    }
    .scroll-container::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera: 隐藏滚动条 */
    }

    .img-box {
      position: relative;
      // overflow: hidden;
      .img-text {
        position: absolute;
        line-height: 1.3;
      }
    }
  }

  .home-title-bg {
    height: 44rpx;
    opacity: 1;
    border-radius: 0rpx 149rpx 115rpx 0rpx;
    background: linear-gradient(
      90deg,
      rgba(198, 254, 94, 0) 0%,
      rgba(198, 254, 94, 1) 100%
    );
    display: flex;
    align-items: center;
    padding-right: 35rpx;
    margin-bottom: 90rpx;

    .line-item {
      width: 12rpx;
      height: 12rpx;
      opacity: 0.55;
      border-radius: 240rpx;
      background: rgba(27, 27, 27, 1);
      margin-right: 8rpx;
    }

    .line-item:nth-child(2) {
      background: rgba(27, 27, 27, 1);
    }

    .line-item:nth-child(3) {
      background: rgba(27, 27, 27, 1);
      margin-right: 0;
    }
  }

  .tagsContent {
    display: flex;
    overflow-x: auto;
    width: 100%;
    white-space: nowrap; /* 防止内容换行 */
    -webkit-overflow-scrolling: touch; /* 提升在移动设备上的滚动性能 */
  }

  .desc-item {
    flex: 0 0 auto; /* 防止子元素伸缩 */
    opacity: 1;
    border-radius: 210rpx;
    background: rgba(235, 247, 244, 0.3);
    padding: 8rpx 16rpx;
    margin-right: 10px; /* 项目之间的间距 */
    .desc-icon {
      border-radius: 4rpx;
      background: rgba(27, 27, 27, 1);
    }
  }

  .tagsContent::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera: 隐藏滚动条 */
  }

  .edit-btn {
    width: 100%;
    margin-top: 25rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .my-nick-pop {
    padding: 20rpx 28rpx;
    .my-nick-pop-title {
      display: flex;
      flex-direction: row;
      justify-content: center;
      width: 600rpx;
      padding-top: 50rpx;
    }
    .my-nick-pop-input {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      padding: 40rpx;
      input {
        flex: 1;
        height: 80rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        color: #555;
        border: 2rpx #eee solid;
        border-radius: 10rpx;
      }
    }
    .my-nick-pop-btn {
      display: flex;
      flex-direction: row;
      border-top-color: #f5f5f5;
      border-top-style: solid;
      border-top-width: 2rpx;
      .my-nick-pop-btn-sure {
        color: #2595f3;
        border-left: 2rpx solid #eee;
      }
      button {
        flex: 1;
        background: transparent;
      }
    }
  }
}
</style>
